package com.yulebaby.callsenter.ui.fragment;

import android.content.Intent;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.Nullable;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.view.View;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.listener.OnItemChildClickListener;
import com.orhanobut.logger.Logger;
import com.yulebaby.callsenter.R;
import com.yulebaby.callsenter.adapter.CallLogAdapter;
import com.yulebaby.callsenter.bean.CallLogBean;
import com.yulebaby.callsenter.bean.CustomerBean;
import com.yulebaby.callsenter.bean.ResultBean;
import com.yulebaby.callsenter.database.manager.Dao;
import com.yulebaby.callsenter.global.App;
import com.yulebaby.callsenter.global.Constant;
import com.yulebaby.callsenter.http.callback.HttpCallback;
import com.yulebaby.callsenter.receiver.JpushReceiver;
import com.yulebaby.callsenter.task.LoginTask;
import com.yulebaby.callsenter.task.UploadCallLogTask;
import com.yulebaby.callsenter.ui.activity.LoginActivity;
import com.yulebaby.callsenter.ui.base.BasicFragment;
import com.yulebaby.callsenter.ui.view.PromptDialog;
import com.yulebaby.callsenter.ui.view.YuLeBaByLinearLayoutManager;
import com.yulebaby.callsenter.utils.JpushUtil;
import com.yulebaby.callsenter.utils.MediaPlayerUtils;
import com.yulebaby.callsenter.utils.SPUtil;
import com.yulebaby.callsenter.utils.ThreadUtils;
import com.yulebaby.callsenter.utils.ToastUtil;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.concurrent.TimeUnit;

import cn.jpush.android.api.JPushInterface;
import cn.jpush.android.api.TagAliasCallback;
import rx.Observable;
import rx.Subscriber;
import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Action1;
import rx.schedulers.Schedulers;

/**
 * Author: Zhangbo   可以使用Rxjava进一步优化 TODO
 * Time: 2016/11/11
 */
public class RecordFragment extends BasicFragment implements SwipeRefreshLayout.OnRefreshListener, MediaPlayerUtils.CompletionListener {
    private List<CallLogBean> callLogList = new ArrayList<>();
    private CallLogAdapter mCallLogAdapter = new CallLogAdapter(callLogList);
    protected RecyclerView mRecyclerView;
    protected SwipeRefreshLayout mSwipeRefresh;
    private View mHeader;
    private boolean isRefresh;

    public static RecordFragment newInstance() {
        Bundle args = new Bundle();
        RecordFragment fragment = new RecordFragment();
        fragment.setArguments(args);
        return fragment;
    }

    private MediaPlayerUtils mPlayerUtils;
    private int lastPosition = -1;
    private CallLogBean mClickCallLogBean;
    private Dao mDao = Dao.getInstance();


    @Override
    public void onLazyInitView(@Nullable Bundle savedInstanceState) {
        super.onLazyInitView(savedInstanceState);
        requestData();
        mPlayerUtils = MediaPlayerUtils.getInstances();
        mPlayerUtils.setOnCompletionListener(this);
        mHeader = mInflater.inflate(R.layout.item_calllog_head, null);
        mCallLogAdapter.addHeaderView(mHeader);
        mRecyclerView.addOnItemTouchListener(new OnItemChildClickListener() {
            @Override
            public void onSimpleItemChildClick(BaseQuickAdapter baseQuickAdapter, View view, int position) {
                mClickCallLogBean = (CallLogBean) baseQuickAdapter.getItem(position);
                if (lastPosition != position) {
                    if (mPlayerUtils.isPlaying() && lastPosition != -1) {
                        mPlayerUtils.pause();
                        (((CallLogBean) baseQuickAdapter.getItem(lastPosition))).setPlayState(2);
                        mCallLogAdapter.notifyDataSetChanged();
                    }
                    lastPosition = position;
                }

                switch (view.getId()) {
                    case R.id.iv_play:
                        switch (mClickCallLogBean.getPlayState()) {
                            case 0:
                                ToastUtil.showToast("没有录音文件");
                                break;
                            case 1:
                                mPlayerUtils.pause();
                                mClickCallLogBean.setPlayState(2);
                                mCallLogAdapter.notifyDataSetChanged();
                                break;
                            case 2:
                                mClickCallLogBean.setPlayState(1);
                                String file_path = mClickCallLogBean.getFile_path();
                                if (file_path.startsWith("http://")) {
                                    mPlayerUtils.openAudio(Uri.parse(file_path));
                                } else {
                                    mPlayerUtils.openAudio(file_path);
                                }
                                mCallLogAdapter.notifyDataSetChanged();
                                break;
                        }
                        break;
                }
            }
        });

        mRecyclerView.setAdapter(mCallLogAdapter);
//        mRecyclerView.addItemDecoration(new RecycleDivider(mActivity, RecycleDivider.VERTICAL_LIST));
    }


    @Override
    public View getSuccessView() {
        View listViewFragment = mInflater.inflate(R.layout.fragment_record, null);
        mRecyclerView = (RecyclerView) listViewFragment.findViewById(R.id.base_recycleview);
        mSwipeRefresh = (SwipeRefreshLayout) listViewFragment.findViewById(R.id.base_refresh);
        mRecyclerView.setHasFixedSize(true);
        mRecyclerView.setLayoutManager(new YuLeBaByLinearLayoutManager(mActivity, LinearLayoutManager.VERTICAL, false));
        initRefresh();
        return listViewFragment;
    }

    @Override
    public void requestData() {
        Observable.create(new Observable.OnSubscribe<List<CallLogBean>>() {
            @Override
            public void call(Subscriber<? super List<CallLogBean>> subscriber) {
                subscriber.onNext(mDao.listCallLogDesAll());
            }
        }).subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(callLogBeen -> {
                    callLogList.clear();
                    callLogList.addAll(callLogBeen);
                    mCallLogAdapter.notifyDataSetChanged();
                    mStateViewLayout.showSuccessView();
                    if (isRefreshing()) {
                        refreshComplete();
                    }
                });
    }

    //下拉刷新
    private void initRefresh() {
        mSwipeRefresh.setOnRefreshListener(this);
        mSwipeRefresh.setColorSchemeResources(R.color.swiperefresh_color1, R.color.swiperefresh_color2,
                R.color.swiperefresh_color3, R.color.swiperefresh_color4);
    }

    protected boolean isRefreshing() {
        return isRefresh;
    }

    protected void refreshComplete() {
        mSwipeRefresh.setRefreshing(false);
        isRefresh = false;
    }

    @Override
    public void onRefresh() {
        mSwipeRefresh.setRefreshing(true);
        isRefresh = true;
        requestData();
    }


    @Override
    public void onDestroy() {
        super.onDestroy();
    }



    @Override
    public void Completion() {
        mClickCallLogBean.setPlayState(2);
        mCallLogAdapter.notifyDataSetChanged();
    }
}
